using Viyi.Util.Extensions;

namespace JamesFan.FetchAreaCodes;

internal class CodeEntry {
    static readonly int[] LevelLengths = new[] { 0, 2, 4, 6, 9, 12 };
    public static uint InferLevel(int idLength) {
        return (uint)(idLength <= 6 ? (idLength + 1) / 2 : (3 + (idLength - 6 + 2) / 3));
    }

    public CodeEntry(CodeEntry? baseEntry, string code, string name, string? link = null) {
        Level = baseEntry?.Let(it => it.Level + 1) ?? 0;
        Code = code;
        Id = code[..LevelLengths[Level]];
        Name = name;
        ParentId = baseEntry?.Id ?? "";
        if (link != null) {
            Uri = baseEntry?.Uri?.Let(baseUri => new Uri(baseUri, link)) ?? new Uri(link);
        }
    }

    public string Id { get; private set; }
    public uint Level { get; private set; }

    public string Code { get; }
    public string Name { get; }
    public string ParentId { get; }

    public Uri? Uri { get; }

    public void FixLevel(uint level) {
        Level = level;
        Id = Code[..LevelLengths[level]];
    }

    public override string ToString() {
        return $"[{ParentId}]({Level}) {Code} => {Name}";
    }
}
